package com.ergwang.controller.admin;

import com.ergwang.Model.Admin;
import com.ergwang.Model.Result;
import com.ergwang.Model.admin.bo.*;
import com.ergwang.Model.admin.vo.AdminLoginVO;
import com.ergwang.service.admin.AdminService;
import com.ergwang.service.admin.AdminServiceImpl;
import com.ergwang.utils.HttpUtils;
import com.google.gson.Gson;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Creat by ergWang
 * Date: 2020/5/27
 * Time: 22:25
 */

@WebServlet("/api/admin/admin/*")
public class AdminServlet extends HttpServlet {

    private AdminService adminService = new AdminServiceImpl();
    Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 既然当前servlet可以处理诸如登陆、查询所有admin、删除admin等操作
        // 那怎么知道当前的请求是什么呢？
        // 有什么API可以区分不同url呢？
        String requestURI = request.getRequestURI();
        // 把 login请求前面的那些 /api/admin/admin  替换为"" ，后续的字符串可以少写点
        String action = requestURI.replace("/api/admin/admin/", "");
        if ("login".equals(action)){
            login(request,response);
        }else if ("getSearchAdmins".equals(action)){
            getSearchAdmins(request,response);
        }else if ("addAdminss".equals(action)){
            addAdminss(request,response);
        }else if ("updateAdminss".equals(action)){
            updateAdminss(request,response);
        }else if ("changePwd".equals(action)){
            changePwd(request,response);
        }else if ("logoutAdmin".equals(action)){
            logoutAdmin(request,response);
        }
    }

    /**
     * 退出登陆,清空session
     * @param request
     * @param response
     */
    private void logoutAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 修改密码
     * @param request
     * @param response
     */
    private void changePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AdminChangePwdBO changePwdBO = gson.fromJson(requestBody, AdminChangePwdBO.class);
        int change = adminService.changePwd(changePwdBO);
        if (change == 1){
            response.getWriter().println(gson.toJson(Result.ok()));
        }else if (change == 404){
            response.getWriter().println(gson.toJson(Result.error("旧密码错误！")));
        }else if (change == 500){
            response.getWriter().println(gson.toJson(Result.error("两次密码不一致！")));
        }else {
            response.getWriter().println(gson.toJson(Result.error("未知错误，密码修改失败！")));
        }
    }

    /**
     * 根据id，将管理员账户修改为请求中携带的json数据
     * 1. 获取请求体，并封装为一个Java对象
     * 2. 根据J请求体中的id 到数据库查询并修改数据
     * 3. 作出响应
     * @param request
     * @param response
     */
    private void updateAdminss(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AdminUpdateBO updateBO = gson.fromJson(requestBody, AdminUpdateBO.class);
        int update = adminService.updateAdminss(updateBO);

        // 判断使用影响了数据
        if (update != 0){
            response.getWriter().println(gson.toJson(Result.ok(update)));
        }else {
            response.getWriter().println(gson.toJson(Result.error("修改失败！请重试")));
        }
    }

    /**
     * 添加管理员账户
     * 1. 浏览器向8804服务端发送一个请求，亲故中携带了一个包含用户昵称参数的json字符串
     * 2. 查询数据库，判断数据库中是否已经存在，如果不存在，则添加   ————>   3. 提示添加成功，然后返回到列表页
     * 2. 如果已经存在，则提示账号已存在，请重试
     * @param request
     * @param response
     */
    private void addAdminss(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AdminAddBO adminAddBO = gson.fromJson(requestBody, AdminAddBO.class);
        int add = adminService.addAdminss(adminAddBO);

        // 判断是否有影响一行，作出响应
        if (add != 0){
            response.getWriter().println(gson.toJson(Result.ok(add)));
        }else {
            response.getWriter().println(gson.toJson(Result.error(",添加失败！")));
        }
    }

    /**
     * 条件查询，查询admin管理员的账户信息
     * 1. 浏览器向8084服务端发送一个请求，请求中携带了一个包含用户昵称参数的json字符串
     * 2. 查询数据库，返回满足条件的数据
     * 3. 根据满足条件的数据作出响应
     * @param request
     * @param response
     */
    private void getSearchAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AdminSearchBO searchBO = gson.fromJson(requestBody, AdminSearchBO.class);
        List<Admin> admins = adminService.getSearchAdmins(searchBO);
        response.getWriter().println(gson.toJson(Result.ok(admins)));
    }


    /**
     * 管理员登陆的具体业务逻辑
     * 1. 浏览器向8084发送一个请求，请求体中携带了用户密码参数（json字符串）
     * 2. 查询数据库，校验当前用户名和密码是否正确
     * 3. 根据结果返回不同的响应
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 取出请求参数——取出请求题中的数据
        // 此时无法使用request.getParamater (因为只能获取 key=value 这样的数据)

        // 获取已经通过HttpUtils转换为Java对象的请求题数据
        String requestBody = HttpUtils.getRequestBody(request);
        // 转为gson
        AdminLoginBO loginBO = gson.fromJson(requestBody, AdminLoginBO.class);

        Admin login = adminService.login(loginBO);

        // 判断是否有获得到一个对象，作出响应
        if (login != null){
            request.getSession().setAttribute("admin",login);
            AdminLoginVO loginVO = new AdminLoginVO();
            loginVO.setToken(login.getNickname());
            loginVO.setName(login.getNickname());
            response.getWriter().println(gson.toJson(Result.ok(loginVO)));
        }else {
            response.getWriter().println(gson.toJson(Result.error(",用户名或密码错误")));
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/admin/", "");
        if ("allAdmins".equals(action)){
            allAdmin(request,response);
        }else if ("deleteAdmins".equals(action)){
            deleteAdmins(request,response);
        }else if ("getAdminsInfo".equals(action)){
            getAdminsInfo(request,response);
        }
    }

    /**
     * 通过传入的id，获取此id对应的用户信息
     * @param request
     * @param response
     * @return id对应的用户信息
     */
    private void getAdminsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Admin admin = new Admin();
        admin.setId(id);
        admin = adminService.getAdminsInfo(admin);
        response.getWriter().println(gson.toJson(Result.ok(admin)));
    }

    /**
     * 根据get请求携带的id，删除指定的管理员账户信息
     * @param request
     * @param response
     */
    private void deleteAdmins(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        int delete = adminService.deleteAdmins(id);
        // 判断是否有影响一行，作出响应
        if (delete != 0){
            response.getWriter().println(gson.toJson(Result.ok(delete)));
        }else {
            response.getWriter().println(gson.toJson(Result.error(",删除失败！")));
        }
    }

    /**
     * 显示所有的admin账户信息
     * 1. 查询数据库，并返回数据
     * 2. 作出响应
     * @param request
     * @param response
     */
    private void allAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Admin> adminsList = adminService.allAdmins();
        Result result = new Result();
        result.setCode(0);
        result.setData(adminsList);
        response.getWriter().println(gson.toJson(result));
    }
}
